package com.qlylkj.lbk.ui.company

import android.view.View
import androidx.lifecycle.Observer
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.forest.core.etx.*
import com.forest.core.util.KeyBoardUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import com.qlylkj.lbk.R
import com.qlylkj.lbk.app.Constant
import com.qlylkj.lbk.app.addHost
import com.qlylkj.lbk.base.BaseVMActivity
import com.qlylkj.lbk.model.bean.Company
import com.qlylkj.lbk.model.bean.DictionaryType
import com.qlylkj.lbk.model.event.LiveEvent
import com.qw.photo.CoCo
import com.qw.photo.callback.GetImageCallBack
import com.qw.photo.pojo.PickResult
import kotlinx.android.synthetic.main.activity_edit_company_info.*
import kotlinx.android.synthetic.main.layout_toolbar.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class EditCompanyInfoActivity : BaseVMActivity<CompanyViewModel>() {

    companion object {

        const val EDIT_COMPANY_INFO = "editCompanyInfo"

        private val companyTypeList = mutableListOf(
            DictionaryType(1, "有限责任公司"),
            DictionaryType(2, "股份有限公司"),
            DictionaryType(3, "国有独资公司")
        )

        private val registrationStatusList = mutableListOf(
            DictionaryType(1, "存续"),
            DictionaryType(2, "在业"),
            DictionaryType(3, "未注销"),
            DictionaryType(4, "注销")
        )
    }

    private val options = mutableMapOf<String, Any>()

    override fun providerVMClass() = CompanyViewModel::class.java

    override fun setLayoutId() = R.layout.activity_edit_company_info

    override fun initView() {
        val editCompany= intent.getBooleanExtra(EDIT_COMPANY_INFO,false)
        LiveEventBus.get(LiveEvent.EDIT_COMPANY_INFO_KEY, Company::class.java)
            .observeSticky(this, Observer<Company> {
              if(intent.getBooleanExtra(EDIT_COMPANY_INFO,false)){
                  setCompanyInfoView(it)
              }
            })
        toolbar.setNavigationOnClickListener { finish() }
        toolbarTitle.text = if(editCompany)"公司信息编辑" else "公司信息录入"
        companyCoverImage.setOnClickListener(onClickListener)
        companyRegisterDateText.setOnClickListener(onClickListener)
        registrationStatusText.setOnClickListener(onClickListener)
        companyTypeText.setOnClickListener(onClickListener)
        saveCompanyInfo.setOnClickListener(onClickListener)
    }

    private fun setCompanyInfoView(company: Company){
        company.apply {
            options["id"] = id
            companyCoverImage.load(this@EditCompanyInfoActivity, faceImg.addHost())
            options["faceImg"] = faceImg
            companyNameEdit.setText(companyName)
            companyLegalPersonEdit.setText(legalPersonInfo)
            companyRegisterDateText.text = establishDate
            options["establishDate"] = establishDate
            registrationStatusText.text = registrationStatus
            options["registrationStatus"] = registrationStatus
            registerCapitalEdit.setText(registeredCapital.toString())
            companyTypeText.text = companyType
            options["companyType"] = companyType
            companyAddressEdit.setText(address)
            unifiedSocialCreditCodeEdit.setText(creditCode)
            taxpayerIdentificationCodeEdit.setText(ein)
            businessRegistrationNumberEdit.setText(registrationNumber)
            organizationCodeEdit.setText(organizationCode)
            businessScopeContentEdit.setText(businessScope)
            companyPhoneNumberEdit.setText(cphone)
            landLineNumberEdit.setText(telphone)
            weiBoNameEdit.setText(microblog)
            weChatOfficialAccountEdit.setText(officialAccounts)
            companyOfficialWebsiteEdit.setText(website)
            companyProfileEdit.setText(companyProfile)
            developmentHistoryContentEdit.setText(development)
        }
    }

    override fun initData() {

    }

    override fun startObserve() {
        super.startObserve()
        mViewModel.apply {
            uploadUiState.observe(this@EditCompanyInfoActivity, Observer { uiModel ->
                uiModel?.run {
                   showError?.let {
                       toast(it)
                   }
                    uploadUrl?.let {
                        if(type == Constant.UploadType.TYPE_COMPANY_COVER){
                            options["faceImg"] = it
                        }
                    }
                }
            })
            uiState.observe(this@EditCompanyInfoActivity, Observer { uiModel ->
                uiModel?.run {
                    showError?.let {
                        toast(it)
                    }
                    if(enterCompanyInfoSuccess){
                        toast("录入公司信息成功!")
                        finish()
                    }
                    if(editCompanyInfoSuccess){
                        toast("编辑公司信息成功!")
                        finish()
                    }
                }
            })
        }
    }

    private val onClickListener = View.OnClickListener {
        when (it.id) {
            R.id.companyCoverImage -> selectCompanyCover()
            R.id.companyRegisterDateText -> selectCompanyRegisterDate()
            R.id.registrationStatusText -> selectRegistrationStatus()
            R.id.companyTypeText -> selectCompanyType()
            R.id.saveCompanyInfo -> saveCompanyInfo()
            else -> { }
        }
    }

    private fun selectCompanyCover(){
        val fileDir = getCacheFile("upload")
        val targetFile = File(fileDir,"companyCover.png")
        CoCo.with(this)
            .pick()
            .targetFile(targetFile)
            .applyWithDispose()
            .start(object : GetImageCallBack<PickResult> {

                override fun onSuccess(data: PickResult) {
                    companyCoverImage.load(this@EditCompanyInfoActivity, data.originUri)
                    data.targetFile?.let {
                        mViewModel.uploadFile(Constant.UploadType.TYPE_COMPANY_COVER,it)
                    }
                }

                override fun onFailed(exception: Exception) {
                    toast("选择异常: $exception")
                }
            })
    }

    private fun selectCompanyRegisterDate() {
        KeyBoardUtil.closeKeyboard(this@EditCompanyInfoActivity)
        TimePickerBuilder(this@EditCompanyInfoActivity, OnTimeSelectListener { date, _ ->
            val establishDate = formatDate(date, SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE))
            companyRegisterDateText.text = establishDate
            options["establishDate"] = establishDate
        }).apply {
            setCancelText(getString(R.string.cancel))//取消按钮文字
            setSubmitText(getString(R.string.confirm))//确认按钮文字
            setTitleText("公司成立日期")
            setSubmitColor(getCompatColor(R.color.text_primary))
            setCancelColor(getCompatColor(R.color.text_content))
            setLineSpacingMultiplier(2.5F)
            isCyclic(true)
            setDividerColor(getCompatColor(R.color.text_primary))
            setTextColorCenter(getCompatColor(R.color.text_primary))
            setTextColorOut(getCompatColor(R.color.text_desc))
            setContentTextSize(20)
            build().show()
        }
    }

    private fun selectRegistrationStatus() {
        KeyBoardUtil.closeKeyboard(this@EditCompanyInfoActivity)
        OptionsPickerBuilder(
            this@EditCompanyInfoActivity,
            OnOptionsSelectListener { options1, _, _, _ ->
                val dictionaryType = registrationStatusList[options1]
                registrationStatusText.text = dictionaryType.name
                options["registrationStatus"] = dictionaryType.name
            }).apply {
            setCancelText(getString(R.string.cancel))//取消按钮文字
            setSubmitText(getString(R.string.confirm))//确认按钮文字
            setTitleText("公司经营状态")
            setSubmitColor(getCompatColor(R.color.colorPrimary))
            setCancelColor(getCompatColor(R.color.text_content))
            setCyclic(false, false, false)
            setLineSpacingMultiplier(2.5F)
            setDividerColor(getCompatColor(R.color.colorPrimary))
            setTextColorCenter(getCompatColor(R.color.colorPrimary))
            setTextColorOut(getCompatColor(R.color.text_desc))
            setContentTextSize(20)
            build<DictionaryType>().run {
                setPicker(registrationStatusList)
                show()
            }
        }
    }

    private fun selectCompanyType() {
        KeyBoardUtil.closeKeyboard(this@EditCompanyInfoActivity)
        OptionsPickerBuilder(
            this@EditCompanyInfoActivity,
            OnOptionsSelectListener { options1, _, _, _ ->
                val dictionaryType = companyTypeList[options1]
                companyTypeText.text = dictionaryType.name
                options["companyType"] = dictionaryType.name
            }).apply {
            setCancelText(getString(R.string.cancel))//取消按钮文字
            setSubmitText(getString(R.string.confirm))//确认按钮文字
            setTitleText("公司类型")
            setSubmitColor(getCompatColor(R.color.colorPrimary))
            setCancelColor(getCompatColor(R.color.text_content))
            setCyclic(false, false, false)
            setLineSpacingMultiplier(2.5F)
            setDividerColor(getCompatColor(R.color.colorPrimary))
            setTextColorCenter(getCompatColor(R.color.colorPrimary))
            setTextColorOut(getCompatColor(R.color.text_desc))
            setContentTextSize(20)
            build<DictionaryType>().run {
                setPicker(companyTypeList)
                show()
            }
        }
    }

    private fun saveCompanyInfo() {
        val companyName = companyNameEdit.toTrim()
        val companyLegalPerson = companyLegalPersonEdit.toTrim()
        val registerCapital = registerCapitalEdit.toTrim()
        val companyAddress = companyAddressEdit.toTrim()
        val unifiedSocialCreditCode = unifiedSocialCreditCodeEdit.toTrim()
        val taxpayerIdentificationCode = taxpayerIdentificationCodeEdit.toTrim()
        val businessRegistrationNumber = businessRegistrationNumberEdit.toTrim()
        val organizationCode = organizationCodeEdit.toTrim()
        val businessScopeContent = businessScopeContentEdit.toTrim()
        val companyPhoneNumber = companyPhoneNumberEdit.toTrim()
        val landLineNumber = landLineNumberEdit.toTrim()
        val weiBoName = weiBoNameEdit.toTrim()
        val weChatOfficialAccount = weChatOfficialAccountEdit.toTrim()
        val companyOfficialWebsite = companyOfficialWebsiteEdit.toTrim()
        val companyProfile = companyProfileEdit.toTrim()
        val developmentHistoryContent = developmentHistoryContentEdit.toTrim()
        if(companyName.isEmpty()){
            toast("请填写公司名称")
            return
        }
        if(companyLegalPerson.isEmpty()){
            toast("请填写公司法人")
            return
        }
        if(companyRegisterDateText.text == "请选择日期"){
            toast("请选择注册日期")
            return
        }
        if(registrationStatusText.text == "请选择登记状态"){
            toast("请选择登记状态")
            return
        }
        if(registerCapital.isEmpty()){
            toast("请填写注册资本")
            return
        }
        if(companyTypeText.text == "请选择公司类型"){
            toast("请选择公司类型")
            return
        }
        if(companyAddress.isEmpty()){
            toast("请填写公司地址")
            return
        }
        if(unifiedSocialCreditCode.isEmpty()){
            toast("请填写统一社会信用代码")
            return
        }
        if(taxpayerIdentificationCode.isEmpty()){
            toast("请填写纳税人识别号")
            return
        }
        if(businessRegistrationNumber.isEmpty()){
            toast("请填写工商注册号")
            return
        }
        if(organizationCode.isEmpty()){
            toast("请填写组织机构代码")
            return
        }
        if(businessScopeContent.isEmpty()){
            toast("请填写公司经营范围")
            return
        }
        if(companyPhoneNumber.isEmpty()){
            toast("请填写手机号码")
            return
        }
        if(landLineNumber.isEmpty()){
            toast("请填写座机号码")
            return
        }
        if(companyOfficialWebsite.isEmpty()){
            toast("请填写公司官网")
            return
        }
        if(companyProfile.isEmpty()){
            toast("请填写公司简介")
            return
        }
        if(developmentHistoryContent.isEmpty()){
            toast("请填写公司发展历程")
            return
        }
        options["inputType"] = 2
        options["companyName"] = companyName
        options["legalPersonInfo"] = companyLegalPerson
        options["ein"] = taxpayerIdentificationCode
        options["address"] = companyAddress
        options["businessScope"] = businessScopeContent
        options["cphone"] = companyPhoneNumber
        options["telphone"] = landLineNumber
        options["website"] = companyOfficialWebsite
        options["officialAccounts"] = weChatOfficialAccount
        options["microblog"] = weiBoName
        options["registeredCapital"] = registerCapital.toInt()
        options["registrationNumber"] = businessRegistrationNumber
        options["organizationCode"] = organizationCode
        options["creditCode"] = unifiedSocialCreditCode
        options["companyProfile"] = companyProfile
        options["development"] = developmentHistoryContent
        if(intent.getBooleanExtra(EDIT_COMPANY_INFO,false)){
            mViewModel.editCompanyInfo(options)
        }else{
            mViewModel.enterCompanyInfo(options)
        }
    }

}